import domToImage from 'dom-to-image';
import printJS from 'print-js';

export const convertToSingleImage = async (
  element: HTMLElement,
): Promise<string | undefined> => {
  try {
    // 将 DOM 元素转换为 PNG 格式的 Base64 图片
    return await domToImage.toPng(element, { bgcolor: 'white' }); // 直接返回 Base64 字符串
  } catch (error) {
    console.error('Error generating image:', error);
  }
};

// 将某个元素转换为单张图片并下载
export const convertToSingleImageAndDownload = async (selector: any) => {
  try {
    const content = document.querySelector(selector);
    const div = document.createElement('div');
    div.innerHTML = content?.innerHTML;
    document.body.append(div);
    await sleep(500);
    const r1: any = div.querySelector('.el-scrollbar__view');
    const r2: any = div.querySelector('.el-table__body');
    if (r1) {
      r1.style.setProperty('width', '100%', 'important');
    }
    if (r2) {
      r2.style.setProperty('width', '100%', 'important');
    }

    await sleep(500);
    const dataUrl = await convertToSingleImage(div);

    // 创建下载链接
    const link: any = document.createElement('a');
    link.href = dataUrl;
    link.download = '报表';
    document.body.append(link);
    link.click(); // 触发下载
    link.remove(); // 清理
    div.remove();
  } catch (error) {
    console.error('Error generating image:', error);
  }
};

export const sleep = (ms: number) =>
  new Promise((resolve) => setTimeout(resolve, ms));

// 将某个元素转换为单张图片并调用浏览器的打印方法
export const convertToSingleImageAndPrint = async (
  selector: any,
  width: any = '100%',
) => {
  try {
    const content = document.querySelector(selector);
    const div = document.createElement('div');
    div.style.width = width;
    div.innerHTML = content?.innerHTML;
    document.body.append(div);
    await sleep(500);
    const r1: any = div.querySelector('.el-scrollbar__view');
    const r2: any = div.querySelector('.el-table__body');
    if (r1) {
      r1.style.setProperty('width', '100%', 'important');
    }
    if (r2) {
      r2.style.setProperty('width', '100%', 'important');
    }

    await sleep(500);
    const dataUrl = await convertToSingleImage(div);

    printJS({ printable: dataUrl, type: 'image', header: '' });
    div.remove();
  } catch (error) {
    console.error('Error generating image:', error);
  }
};
